home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / jockey / ui.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  30.0 KB  |  833 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Abstract user interface, which provides all logic and strings.
  5.  
  6. Concrete implementations need to implement a set of abstract presentation
  7. functions with an appropriate toolkit.
  8. '''
  9. import gettext
  10. import optparse
  11. import urllib2
  12. import tempfile
  13. import sys
  14. import time
  15. import os
  16. import threading
  17. import gobject
  18. import dbus
  19. import dbus.service as dbus
  20. import dbus.mainloop.glib as dbus
  21. from oslib import OSLib
  22. from backend import UnknownHandlerException, PermissionDeniedByPolicy, BackendCrashError, polkit_auth_wrapper, dbus_sync_call_signal_wrapper, Backend, DBUS_BUS_NAME
  23.  
  24. def bool(str):
  25.     '''Convert backend encoding of a boolean to a real boolean.'''
  26.     if str == 'True':
  27.         return True
  28.     if not str == 'False':
  29.         raise AssertionError
  30.     return False
  31.  
  32.  
  33. def __fix_stdouterr():
  34.     import codecs
  35.     import locale
  36.     
  37.     def null_decode(input, errors = 'strict'):
  38.         return (input, len(input))
  39.  
  40.     sys.stdout = codecs.EncodedFile(sys.stdout, locale.getpreferredencoding())
  41.     sys.stdout.decode = null_decode
  42.     sys.stderr = codecs.EncodedFile(sys.stderr, locale.getpreferredencoding())
  43.     sys.stderr.decode = null_decode
  44.  
  45. __fix_stdouterr()
  46.  
  47. class AbstractUI(dbus.service.Object):
  48.     '''Abstract user interface.
  49.  
  50.     This encapsulates the entire program logic and all strings, but does not
  51.     implement any concrete user interface.
  52.     '''
  53.     
  54.     def __init__(self):
  55.         '''Initialize system.
  56.         
  57.         This parses command line arguments, detects available hardware,
  58.         and already installed drivers and handlers.
  59.         '''
  60.         gettext.install('jockey', unicode = True)
  61.         (self.argv_options, self.argv_args) = self.parse_argv()
  62.         if self.argv_options.check:
  63.             time.sleep(self.argv_options.check)
  64.         
  65.         self.init_strings()
  66.         self._dbus_iface = None
  67.         self.dbus_server_main_loop = None
  68.         self.have_ui = False
  69.         self.current_search = (None, None)
  70.  
  71.     
  72.     def backend(self):
  73.         '''Return D-BUS backend client interface.
  74.  
  75.         This gets initialized lazily.
  76.         '''
  77.         if self._dbus_iface is None:
  78.             
  79.             try:
  80.                 self._dbus_iface = Backend.create_dbus_client()
  81.             except Exception:
  82.                 e = None
  83.                 if hasattr(e, '_dbus_error_name') and e._dbus_error_name == 'org.freedesktop.DBus.Error.FileNotFound':
  84.                     if self.have_ui:
  85.                         self.error_message(self._('Cannot connect to D-BUS'), str(e))
  86.                     else:
  87.                         self.error_msg(str(e))
  88.                     sys.exit(1)
  89.                 else:
  90.                     raise 
  91.                 e._dbus_error_name == 'org.freedesktop.DBus.Error.FileNotFound'
  92.  
  93.             self._call_progress_dialog(self._('Searching for available drivers...'), self._dbus_iface.detect, timeout = 600)
  94.         else:
  95.             
  96.             try:
  97.                 self._dbus_iface.handler_info(' ')
  98.             except Exception:
  99.                 e = None
  100.                 if hasattr(e, '_dbus_error_name') and e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
  101.                     self._dbus_iface = Backend.create_dbus_client()
  102.                     self._call_progress_dialog(self._('Searching for available drivers...'), self._dbus_iface.detect, timeout = 600)
  103.                 
  104.             except:
  105.                 e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown'
  106.  
  107.         return self._dbus_iface
  108.  
  109.     
  110.     def _(self, str, convert_keybindings = False):
  111.         """Keyboard accelerator aware gettext() wrapper.
  112.         
  113.         This optionally converts keyboard accelerators to the appropriate
  114.         format for the frontend.
  115.  
  116.         All strings in the source code should use the '_' prefix for key
  117.         accelerators (like in GTK). For inserting a real '_', use '__'.
  118.         """
  119.         result = _(str)
  120.         if convert_keybindings:
  121.             result = self.convert_keybindings(result)
  122.         
  123.         return result
  124.  
  125.     
  126.     def init_strings(self):
  127.         '''Initialize all static strings which are used in UI implementations.'''
  128.         self.string_handler = self._('Component')
  129.         self.string_button_enable = self._('_Enable', True)
  130.         self.string_button_disable = self._('_Disable', True)
  131.         self.string_enabled = self._('Enabled')
  132.         self.string_disabled = self._('Disabled')
  133.         self.string_status = self._('Status')
  134.         self.string_restart = self._('Needs computer restart')
  135.         self.string_in_use = self._('In use')
  136.         self.string_not_in_use = self._('Not in use')
  137.         self.string_license_label = self._('License:')
  138.         self.string_details = self._('details')
  139.         self.string_free = self._('Free')
  140.         self.string_restricted = self._('Proprietary')
  141.         self.string_download_progress_title = self._('Download in progress')
  142.         self.string_unknown_driver = self._('Unknown driver')
  143.         self.string_unprivileged = self._('You are not authorized to perform this action.')
  144.         self.string_support_certified = self._('Tested by the %s developers') % OSLib.inst.os_vendor
  145.         self.string_support_uncertified = self._('Not tested by the %s developers') % OSLib.inst.os_vendor
  146.         self.string_recommended = self._('Recommended')
  147.         self.string_license_dialog_title = self._('License Text for Device Driver')
  148.  
  149.     
  150.     def main_window_title(self):
  151.         '''Return an appropriate translated window title.
  152.  
  153.         This might depend on the mode the program is called (e. g. showing only
  154.         free drivers, only restricted ones, etc.).
  155.         '''
  156.         if self.argv_options.mode == 'nonfree':
  157.             return self._('Restricted Hardware Drivers')
  158.         return self._('Hardware Drivers')
  159.  
  160.     
  161.     def main_window_text(self):
  162.         '''Return a tuple (heading, subtext) of main window texts.
  163.  
  164.         This changes depending on whether restricted or free drivers are
  165.         used/available, or if a search is currently running. Thus the UI should
  166.         update it whenever it changes a handler.
  167.         '''
  168.         if self.current_search[0]:
  169.             return (self._('Driver search results'), self.hwid_to_display_string(self.current_search[0]))
  170.         proprietary_in_use = False
  171.         proprietary_available = False
  172.         for h_id in self.backend().available(self.argv_options.mode):
  173.             info = self.backend().handler_info(h_id)
  174.             if not bool(info['free']):
  175.                 proprietary_available = True
  176.                 if bool(info['used']):
  177.                     proprietary_in_use = True
  178.                     break
  179.                 
  180.             bool(info['used'])
  181.         
  182.         if proprietary_in_use:
  183.             heading = self._('Proprietary drivers are being used to make this computer work properly.')
  184.         else:
  185.             heading = self._('No proprietary drivers are in use on this system.')
  186.         if proprietary_available:
  187.             subtext = self._('Proprietary drivers do not have public source code that %(os)s developers are free to modify. They represent a risk to you because they are only available on the types of computer chosen by the manufacturer, and security updates to them depend solely on the responsiveness of the manufacturer. %(os)s cannot fix or improve these drivers.') % {
  188.                 'os': OSLib.inst.os_vendor }
  189.         else:
  190.             subtext = ''
  191.         return (heading, subtext)
  192.  
  193.     
  194.     def get_handler_category(self, handler_id):
  195.         '''Return string for handler category.'''
  196.         if handler_id.startswith('xorg:'):
  197.             return self._('Graphics driver')
  198.         if handler_id.startswith('firmware:'):
  199.             return self._('Firmware')
  200.         return self._('Device driver')
  201.  
  202.     
  203.     def get_ui_driver_name(self, handler_info):
  204.         '''Return handler name, as it should be presented in the UI.
  205.         
  206.         This cares about translation, as well as tagging recommended drivers.
  207.         '''
  208.         result = handler_info['name']
  209.         result = self._(result)
  210.         if 'version' in handler_info:
  211.             result += ' (%s)' % self._('version %s') % handler_info['version']
  212.         
  213.         if bool(handler_info['recommended']):
  214.             result += ' [%s]' % self.string_recommended
  215.         
  216.         return result
  217.  
  218.     
  219.     def get_ui_driver_info(self, handler_id):
  220.         '''Get strings and icon types for displaying driver information.
  221.         
  222.         If handler_id is None, this returns empty strings, suitable for
  223.         displaying if no driver is selected, and "None" for the bool values,
  224.         (UIs should disable the corresponding UI element then).
  225.         
  226.         This returns a mapping with the following keys: name (string),
  227.         description (string), certified (bool, for icon), certification_label
  228.         (label string), free (bool, for icon), license_label
  229.         (Free/Proprietary, label string), license_text (string, might be
  230.         empty), enabled (bool, for icon), used (bool), needs_reboot(bool),
  231.         status_label (label string), button_toggle_label (string)'''
  232.         if not handler_id:
  233.             return {
  234.                 'name': '',
  235.                 'description': '',
  236.                 'free': None,
  237.                 'enabled': None,
  238.                 'used': None,
  239.                 'license_text': '',
  240.                 'status_label': '',
  241.                 'license_label': '',
  242.                 'certified': None,
  243.                 'certification_label': '',
  244.                 'button_toggle_label': None }
  245.         info = polkit_auth_wrapper(self.backend().handler_info, handler_id)
  246.         result = {
  247.             'name': self.get_ui_driver_name(info),
  248.             'description': self._get_description_rationale_text(info),
  249.             'free': bool(info['free']),
  250.             'enabled': bool(info['enabled']),
  251.             'used': bool(info['used']),
  252.             'needs_reboot': False,
  253.             'license_text': info.get('license', '') }
  254.         if result['free']:
  255.             result['license_label'] = self.string_free
  256.         else:
  257.             result['license_label'] = self.string_restricted
  258.         if 'repository' not in info:
  259.             result['certified'] = True
  260.             result['certification_label'] = self.string_support_certified
  261.         else:
  262.             result['certified'] = False
  263.             result['certification_label'] = self.string_support_uncertified
  264.         if result['enabled']:
  265.             if 'package' in info:
  266.                 result['button_toggle_label'] = self._('_Remove', True)
  267.             else:
  268.                 result['button_toggle_label'] = self._('_Deactivate', True)
  269.             if result['used']:
  270.                 result['status_label'] = self._('This driver is activated and currently in use.')
  271.             elif bool(info['changed']):
  272.                 result['needs_reboot'] = True
  273.                 result['status_label'] = self._('You need to restart the computer to activate this driver.')
  274.             else:
  275.                 result['status_label'] = self._('This driver is activated but not currently in use.')
  276.         else:
  277.             result['button_toggle_label'] = self._('_Activate', True)
  278.             if result['used']:
  279.                 if bool(info['changed']):
  280.                     result['needs_reboot'] = True
  281.                     result['status_label'] = self._('This driver was just disabled, but is still in use.')
  282.                 else:
  283.                     result['status_label'] = self._('A different version of this driver is in use.')
  284.             else:
  285.                 result['status_label'] = self._('This driver is not activated.')
  286.         return result
  287.  
  288.     
  289.     def parse_argv(self):
  290.         '''Parse command line arguments, and return (options, args) pair.'''
  291.         
  292.         def check_option_callback(option, opt_str, value, parser):
  293.             if len(parser.rargs) > 0 and parser.rargs[0].isdigit():
  294.                 setattr(parser.values, 'check', int(parser.rargs.pop(0)))
  295.             else:
  296.                 setattr(parser.values, 'check', 0)
  297.  
  298.         parser = optparse.OptionParser()
  299.         parser.set_defaults(check = None)
  300.         parser.add_option('-c', '--check', action = 'callback', callback = check_option_callback, help = self._('Check for newly used or usable drivers and notify the user.'))
  301.         parser.add_option('-u', '--update-db', action = 'store_true', dest = 'update_db', default = False, help = self._('Query driver databases for newly available or updated drivers.'))
  302.         parser.add_option('-l', '--list', action = 'store_true', dest = 'list', default = False, help = self._('List available drivers and their status.'))
  303.         parser.add_option('--hardware-ids', action = 'store_true', dest = 'list_hwids', default = False, help = self._('List hardware identifiers from this system.'))
  304.         parser.add_option('-e', '--enable', type = 'string', dest = 'enable', default = None, metavar = 'DRIVER', help = self._('Enable a driver'))
  305.         parser.add_option('-d', '--disable', type = 'string', dest = 'disable', default = None, metavar = 'DRIVER', help = self._('Disable a driver'))
  306.         parser.add_option('--confirm', action = 'store_true', dest = 'confirm', default = False, help = self._('Ask for confirmation for --enable/--disable'))
  307.         parser.add_option('-C', '--check-composite', action = 'store_true', dest = 'check_composite', default = False, help = self._('Check if there is a graphics driver available that supports composite and offer to enable it'))
  308.         parser.add_option('-m', '--mode', type = 'choice', dest = 'mode', default = 'any', choices = [
  309.             'free',
  310.             'nonfree',
  311.             'any'], metavar = 'free|nonfree|any', help = self._('Only manage free/nonfree drivers. By default, all available drivers with any license are presented.'))
  312.         parser.add_option('--dbus-server', action = 'store_true', dest = 'dbus_server', default = False, help = self._('Run as session D-BUS server.'))
  313.         (opts, args) = parser.parse_args()
  314.         return (opts, args)
  315.  
  316.     
  317.     def run(self):
  318.         '''Evaluate command line arguments and do the appropriate action.
  319.  
  320.         If no argument was specified, this starts the interactive UI.
  321.         
  322.         This returns the exit code of the program.
  323.         '''
  324.         if self.argv_options.update_db:
  325.             polkit_auth_wrapper(self.backend().update_driverdb)
  326.             return 0
  327.         if self.argv_options.list:
  328.             self.list()
  329.             return 0
  330.         if self.argv_options.list_hwids:
  331.             self.list_hwids()
  332.             return 0
  333.         if self.argv_options.dbus_server:
  334.             self.dbus_server()
  335.             return 0
  336.         if self.argv_options.check is not None:
  337.             if self.check():
  338.                 return 0
  339.             return 1
  340.         self.argv_options.check is not None
  341.         self.ui_init()
  342.         self.have_ui = True
  343.         if self.argv_options.enable:
  344.             if self.set_handler_enable(self.argv_options.enable, 'enable', self.argv_options.confirm, False):
  345.                 return 0
  346.             return 1
  347.         self.argv_options.enable
  348.         if self.argv_options.disable:
  349.             if self.set_handler_enable(self.argv_options.disable, 'disable', self.argv_options.confirm, False):
  350.                 return 0
  351.             return 1
  352.         self.argv_options.disable
  353.         if self.argv_options.check_composite:
  354.             if self.check_composite():
  355.                 return 0
  356.             return 1
  357.         self.argv_options.check_composite
  358.         self.ui_show_main()
  359.         return self.ui_main_loop()
  360.  
  361.     
  362.     def list(self):
  363.         '''Print a list of available handlers and their status to stdout.'''
  364.         for h_id in self.backend().available(self.argv_options.mode):
  365.             i = self.backend().handler_info(h_id)
  366.             if not bool(i['free']) or self.string_free:
  367.                 pass
  368.             if not bool(i['enabled']) or self.string_enabled:
  369.                 pass
  370.             if not bool(i['used']) or self.string_in_use:
  371.                 pass
  372.             print '%s - %s (%s, %s, %s)' % (h_id, i['name'], self.string_restricted, self.string_disabled, self.string_not_in_use)
  373.         
  374.  
  375.     
  376.     def list_hwids(self):
  377.         '''Print a list of available handlers and their status to stdout.'''
  378.         for h_id in self.backend().get_hardware():
  379.             print h_id
  380.         
  381.  
  382.     
  383.     def check(self):
  384.         '''Notify the user about newly used or available drivers since last check().
  385.         
  386.         Return True if any new driver is available which is not yet enabled.
  387.         '''
  388.         
  389.         try:
  390.             (new_used, new_avail) = polkit_auth_wrapper(self.backend().new_used_available, self.argv_options.mode)
  391.         except PermissionDeniedByPolicy:
  392.             self.error_msg(self.string_unprivileged)
  393.             return False
  394.  
  395.         restricted_available = False
  396.         for h_id in set(new_avail):
  397.             info = self.backend().handler_info(h_id)
  398.             if not bool(info['announce']):
  399.                 new_avail.remove(h_id)
  400.                 continue
  401.             
  402.             if not bool(info['free']):
  403.                 restricted_available = True
  404.                 break
  405.                 continue
  406.         
  407.         for h_id in new_used + []:
  408.             if bool(self.backend().handler_info(h_id)['free']):
  409.                 new_used.remove(h_id)
  410.                 continue
  411.         
  412.         notified = False
  413.         if new_avail or new_used:
  414.             self.ui_init()
  415.             self.have_ui = True
  416.         
  417.         if new_avail:
  418.             if restricted_available:
  419.                 self.ui_notification(self._('Restricted drivers available'), self._('In order to use your hardware more efficiently, you can enable drivers which are not free software.'))
  420.             else:
  421.                 self.ui_notification(self._('New drivers available'), self._('There are new or updated drivers available for your hardware.'))
  422.             notified = True
  423.         elif new_used:
  424.             self.ui_notification(self._('New restricted drivers in use'), self._('In order for this computer to function properly, %(os)s is using driver software that cannot be supported by %(os)s.') % {
  425.                 'os': OSLib.inst.os_vendor })
  426.             notified = True
  427.         
  428.         if notified:
  429.             self.ui_main_loop()
  430.         
  431.         return len(new_avail) > 0
  432.  
  433.     
  434.     def check_composite(self):
  435.         '''Check for a composite-enabling X.org driver.
  436.  
  437.         If one is available and not installed, offer to install it and return
  438.         True if installation succeeded. Otherwise return False.
  439.         '''
  440.         h_id = self.backend().check_composite()
  441.         if h_id:
  442.             self.set_handler_enable(h_id, 'enable', True)
  443.             return bool(self.backend().handler_info(h_id)['enabled'])
  444.         self.error_msg(self._('There is no available graphics driver for your system which supports the composite extension, or the current one already supports it.'))
  445.         return False
  446.  
  447.     
  448.     def _install_progress_handler(self, phase, cur, total):
  449.         if not self._install_progress_shown:
  450.             self.ui_progress_start('', self._('Downloading and installing driver...'), total)
  451.             self._install_progress_shown = True
  452.         
  453.         self.ui_progress_update(cur, total)
  454.         self.ui_idle()
  455.  
  456.     
  457.     def _remove_progress_handler(self, cur, total):
  458.         if not self._install_progress_shown:
  459.             self.ui_progress_start('', self._('Removing driver...'), total)
  460.             self._install_progress_shown = True
  461.         
  462.         self.ui_progress_update(cur, total)
  463.         self.ui_idle()
  464.  
  465.     
  466.     def set_handler_enable(self, handler_id, action, confirm, gui = True):
  467.         """Enable, disable, or toggle a handler.
  468.  
  469.         action can be 'enable', 'disable', or 'toggle'. If confirm is True,
  470.         this first presents a confirmation dialog. Then a progress dialog is
  471.         presented for installation/removal of the handler.
  472.  
  473.         If gui is True, error messags and install progress will be shown
  474.         in the GUI, otherwise just printed to stderr (CLI mode).
  475.  
  476.         Return True if anything was changed and thus the UI needs to be
  477.         refreshed.
  478.         """
  479.         
  480.         try:
  481.             i = polkit_auth_wrapper(self.backend().handler_info, handler_id)
  482.         except UnknownHandlerException:
  483.             self.error_msg('%s: %s' % (self.string_unknown_driver, handler_id))
  484.             self.error_msg(self._('Use --list to see available drivers'))
  485.             return False
  486.  
  487.         if action == 'enable':
  488.             enable = True
  489.         elif action == 'disable':
  490.             enable = False
  491.         elif action == 'toggle':
  492.             enable = not bool(i['enabled'])
  493.         else:
  494.             raise ValueError, 'invalid action %s; allowed are enable, disable, toggle'
  495.         if action == 'enable' in i:
  496.             msg = i['can_change']
  497.             if gui:
  498.                 self.error_message(self._('Cannot change driver'), self._(msg))
  499.             else:
  500.                 self.error_msg(self._(msg))
  501.             return False
  502.         if enable == bool(i['enabled']):
  503.             return False
  504.         
  505.         try:
  506.             if gui:
  507.                 
  508.                 try:
  509.                     self._install_progress_shown = False
  510.                     polkit_auth_wrapper(dbus_sync_call_signal_wrapper, self.backend(), 'set_enabled', {
  511.                         'install_progress': self._install_progress_handler,
  512.                         'remove_progress': self._remove_progress_handler }, handler_id, enable)
  513.                 finally:
  514.                     pass
  515.  
  516.             else:
  517.                 polkit_auth_wrapper(self.backend().set_enabled, handler_id, enable)
  518.         except PermissionDeniedByPolicy:
  519.             None if confirm else None if enable else action == 'enable' in i
  520.             None if confirm else None if enable else action == 'enable' in i
  521.             self.error_message('', self.string_unprivileged)
  522.             return False
  523.             except BackendCrashError:
  524.                 self._dbus_iface = None
  525.                 self.error_message('', '%s\n\n  ubuntu-bug jockey-common\n\n%s' % (self._('Sorry, the Jockey backend crashed. Please file a bug at:'), self._('Trying to recover by restarting backend.')))
  526.                 return False
  527.                 except SystemError:
  528.                     e = None
  529.                     self.error_message('', str(e).splitlines()[-1])
  530.                     return False
  531.                 else:
  532.                     newstate = bool(self.backend().handler_info(handler_id)['enabled'])
  533.                     return i['enabled'] != newstate
  534.  
  535.  
  536.     
  537.     def _get_description_rationale_text(self, h_info):
  538.         d = h_info.get('description', '')
  539.         r = h_info.get('rationale', '')
  540.         if d:
  541.             d = self._(d)
  542.         
  543.         if r:
  544.             r = self._(r)
  545.         
  546.         if d and r:
  547.             return d.strip() + '\n\n' + r
  548.         if d:
  549.             return d
  550.         if r:
  551.             return r
  552.         return ''
  553.  
  554.     
  555.     def download_url(self, url, filename = None, data = None):
  556.         '''Download an URL into a local file, and display a progress dialog.
  557.         
  558.         If filename is not given, a temporary file will be created.
  559.  
  560.         Additional POST data can be submitted for HTTP requests in the data
  561.         argument (see urllib2.urlopen).
  562.  
  563.         Return (filename, headers) tuple, or (None, headers) if the user
  564.         cancelled the download.
  565.         '''
  566.         block_size = 8192
  567.         current_size = 0
  568.         
  569.         try:
  570.             f = urllib2.urlopen(url)
  571.         except Exception:
  572.             e = None
  573.             self.error_message(self._('Download error'), str(e))
  574.             return (None, None)
  575.  
  576.         headers = f.info()
  577.         if 'Content-Length' in headers:
  578.             total_size = int(headers['Content-Length'])
  579.         else:
  580.             total_size = -1
  581.         self.ui_progress_start(self.string_download_progress_title, url, total_size)
  582.         if filename:
  583.             tfp = open(filename, 'wb')
  584.             result_filename = filename
  585.         else:
  586.             (fd, result_filename) = tempfile.mkstemp()
  587.             tfp = os.fdopen(fd, 'wb')
  588.         
  589.         try:
  590.             while current_size < total_size:
  591.                 block = f.read(block_size)
  592.                 tfp.write(block)
  593.                 current_size += len(block)
  594.                 if self.ui_progress_update(current_size, total_size):
  595.                     if not filename:
  596.                         os.unlink(result_filename)
  597.                     
  598.                     result_filename = None
  599.                     break
  600.                     continue
  601.         finally:
  602.             tfp.close()
  603.             f.close()
  604.             self.ui_progress_finish()
  605.  
  606.         return (result_filename, headers)
  607.  
  608.     
  609.     def error_msg(klass, msg):
  610.         '''Print msg to stderr, and intercept IOErrors.'''
  611.         
  612.         try:
  613.             print >>sys.stderr, msg
  614.         except IOError:
  615.             pass
  616.  
  617.  
  618.     error_msg = classmethod(error_msg)
  619.     
  620.     def _call_progress_dialog(self, message, fn, *args, **kwargs):
  621.         '''Call fn(*args, **kwargs) while showing a progress dialog.'''
  622.         if not self.have_ui:
  623.             return fn(*args, **kwargs)
  624.         progress_shown = False
  625.         t_fn = threading.Thread(None, fn, 'thread_call_progress_dialog', args, kwargs)
  626.         t_fn.start()
  627.         while True:
  628.             t_fn.join(0.2)
  629.             if not t_fn.isAlive():
  630.                 break
  631.             
  632.             if not progress_shown:
  633.                 progress_shown = True
  634.                 self.ui_progress_start('', message, -1)
  635.             
  636.             if self.ui_progress_update(-1, -1):
  637.                 sys.exit(1)
  638.             
  639.             self.ui_idle()
  640.         if progress_shown:
  641.             self.ui_progress_finish()
  642.             self.ui_idle()
  643.         
  644.  
  645.     
  646.     def get_displayed_handlers(self):
  647.         '''Return the list of displayed handler IDs.
  648.  
  649.         This can either be a list of drivers which match your system, or which
  650.         match a search_driver() invocation.
  651.         '''
  652.         if self.current_search[0]:
  653.             return self.current_search[1]
  654.         return self.backend().available(self.argv_options.mode)
  655.  
  656.     
  657.     def hwid_to_display_string(self, hwid):
  658.         '''Convert a type:value hardware ID string to a human friendly text.'''
  659.         
  660.         try:
  661.             (type, value) = hwid.split(':', 1)
  662.         except ValueError:
  663.             return hwid
  664.  
  665.         if type == 'printer_deviceid':
  666.             
  667.             try:
  668.                 import cupshelpers
  669.             except ImportError:
  670.                 return hwid
  671.  
  672.             info = cupshelpers.parseDeviceID(value)
  673.             return info['MFG'] + ' ' + info['MDL']
  674.         return hwid
  675.  
  676.     DBUS_INTERFACE_NAME = 'com.ubuntu.DeviceDriver'
  677.     
  678.     def dbus_server(self):
  679.         '''Run session D-BUS server backend.'''
  680.         dbus.mainloop.glib.DBusGMainLoop(set_as_default = True)
  681.         bus = dbus.SessionBus()
  682.         dbus_name = dbus.service.BusName(DBUS_BUS_NAME, bus)
  683.         dbus.service.Object.__init__(self, bus, '/GUI')
  684.         self.dbus_server_main_loop = gobject.MainLoop()
  685.         self.dbus_server_main_loop.run()
  686.  
  687.     
  688.     def get_dbus_client(klass):
  689.         '''Return a dbus.Interface object for the server.'''
  690.         obj = dbus.SessionBus().get_object(DBUS_BUS_NAME, '/GUI')
  691.         return dbus.Interface(obj, AbstractUI.DBUS_INTERFACE_NAME)
  692.  
  693.     get_dbus_client = classmethod(get_dbus_client)
  694.     
  695.     def search_driver(self, hwid, sender = None, conn = None):
  696.         '''Search configured driver DBs for a particular hardware component.
  697.  
  698.         The hardware component is described as HardwareID type and value,
  699.         separated by a colon. E. g.  "modalias:pci:12345" or
  700.         "printer_deviceid:MFG:FooTech;MDL:X-12;CMD:GDI". This searches the
  701.         enabled driver databases for a matching driver. If it finds one, it
  702.         offers it to the user. This returns a pair (success, files); where
  703.         \'success\' is True if a driver was found, acknowledged by the user, and
  704.         installed, otherwise False; "files" is the list of files shipped by the
  705.         newly installed packages (useful for e. g. printer drivers to get a
  706.         list of PPDs to check).
  707.         '''
  708.         self.ui_init()
  709.         self.have_ui = True
  710.         b = self.backend()
  711.         
  712.         def _srch():
  713.             if hasattr(b, '_locations'):
  714.                 drivers = self._dbus_iface.search_driver(hwid, timeout = 600)
  715.             else:
  716.                 drivers = b.search_driver(hwid)
  717.             self.current_search = (hwid, drivers)
  718.  
  719.         self._call_progress_dialog(self._('Searching driver for %s...') % self.hwid_to_display_string(hwid), _srch)
  720.         result = False
  721.         files = []
  722.         if self.current_search[1]:
  723.             self.ui_show_main()
  724.             self.ui_main_loop()
  725.             for d in self.current_search[1]:
  726.                 info = self.backend().handler_info(d)
  727.                 if bool(info['enabled']) and bool(info['changed']):
  728.                     result = True
  729.                     if 'package' in info:
  730.                         files += self.backend().handler_files(d)
  731.                     
  732.                 'package' in info
  733.             
  734.         
  735.         if self.dbus_server_main_loop:
  736.             self.dbus_server_main_loop.quit()
  737.         
  738.         return (result, files)
  739.  
  740.     search_driver = dbus.service.method(DBUS_INTERFACE_NAME, in_signature = 's', out_signature = 'bas', sender_keyword = 'sender', connection_keyword = 'conn')(search_driver)
  741.     
  742.     def convert_keybindings(self, str):
  743.         """Convert keyboard accelerators to the particular UI's format.
  744.  
  745.         The abstract UI and drivers use the '_' prefix to mark a keyboard
  746.         accelerator.
  747.  
  748.         A double underscore ('__') is converted to a real '_'."""
  749.         raise NotImplementedError, 'subclasses need to implement this'
  750.  
  751.     
  752.     def ui_init(self):
  753.         '''Initialize UI.
  754.  
  755.         This should load the GUI components, such as glade files, but not show
  756.         the main window yet; that is done by ui_show_main().
  757.         '''
  758.         raise NotImplementedError, 'subclasses need to implement this'
  759.  
  760.     
  761.     def ui_show_main(self):
  762.         '''Show main window.
  763.  
  764.         This should set up presentation of handlers and show the main
  765.         window. This must be called after ui_init().
  766.         '''
  767.         raise NotImplementedError, 'subclasses need to implement this'
  768.  
  769.     
  770.     def ui_main_loop(self):
  771.         '''Main loop for the user interface.
  772.         
  773.         This should return if the user wants to quit the program, and return
  774.         the exit code.
  775.         '''
  776.         raise NotImplementedError, 'subclasses need to implement this'
  777.  
  778.     
  779.     def error_message(self, title, text):
  780.         '''Present an error message box.'''
  781.         raise NotImplementedError, 'subclasses need to implement this'
  782.  
  783.     
  784.     def confirm_action(self, title, text, subtext = None, action = None):
  785.         """Present a confirmation dialog.
  786.  
  787.         If action is given, it is used as button label instead of the default
  788.         'OK'.  Return True if the user confirms, False otherwise.
  789.         """
  790.         raise NotImplementedError, 'subclasses need to implement this'
  791.  
  792.     
  793.     def ui_notification(self, title, text):
  794.         '''Present a notification popup.
  795.  
  796.         This should preferably create a tray icon. Clicking on the tray icon or
  797.         notification should run the GUI.
  798.         '''
  799.         raise NotImplementedError, 'subclasses need to implement this'
  800.  
  801.     
  802.     def ui_idle(self):
  803.         '''Process pending UI events and return.
  804.  
  805.         This is called while waiting for external processes such as package
  806.         installers.
  807.         '''
  808.         raise NotImplementedError, 'subclasses need to implement this'
  809.  
  810.     
  811.     def ui_progress_start(self, title, description, total):
  812.         '''Create a progress dialog.'''
  813.         raise NotImplementedError, 'subclasses need to implement this'
  814.  
  815.     
  816.     def ui_progress_update(self, current, total):
  817.         '''Update status of current progress dialog.
  818.         
  819.         current/total specify the number of steps done and total steps to
  820.         do, or -1 if it cannot be determined. In this case the dialog should
  821.         display an indeterminated progress bar (bouncing back and forth).
  822.  
  823.         This should return True to cancel, and False otherwise.
  824.         '''
  825.         raise NotImplementedError, 'subclasses need to implement this'
  826.  
  827.     
  828.     def ui_progress_finish(self):
  829.         '''Close the current progress dialog.'''
  830.         raise NotImplementedError, 'subclasses need to implement this'
  831.  
  832.  
  833.